package edu.whu.zqm.assignment7.monitor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class ServiceMonitorAdvice {
    private final ServiceMonitor serviceMonitor;

    public ServiceMonitorAdvice(ServiceMonitor serviceMonitor) {
        this.serviceMonitor = serviceMonitor;
    }

    @Around("execution(public * edu.whu.zqm.assignment7.service.*Service.*(..))")
    public Object monitor(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object retVal;
        try {
            retVal = proceedingJoinPoint.proceed();
        } catch (Exception e) {
            serviceMonitor.addMethod(proceedingJoinPoint.getSignature().toString(), 0, true);
            throw e;
        }
        long endTime = System.currentTimeMillis();
        long timeElapsed = endTime - startTime;
        serviceMonitor.addMethod(proceedingJoinPoint.getSignature().toString(), timeElapsed, false);

        return retVal;
    }
}
